# -*- encoding: utf-8 -*-
"""
=======================
Multi-output Regression
=======================

The following example shows how to fit a multioutput regression model with
*auto-sklearn*.
"""
import numpy as np
from pprint import pprint

from sklearn.datasets import make_regression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split

from autosklearn.regression import AutoSklearnRegressor


############################################################################
# Data Loading & Analysis
# =======================

print("="*60)
print("多输出回归数据集详细分析")
print("="*60)

# 生成合成数据集
X, y = make_regression(n_samples=1000, n_features=10, n_informative=5, n_targets=3, random_state=42)

print(f"\n📊 数据集基本信息：")
print(f"特征矩阵 X 的形状: {X.shape}")
print(f"目标矩阵 y 的形状: {y.shape}")
print(f"数据类型: {X.dtype}")

print(f"\n🔍 前3个样本的特征数据 (X):")
for i in range(3):
    print(f"样本{i+1}: {X[i][:5].round(3)}... (显示前5个特征)")

print(f"\n🎯 前3个样本的目标数据 (y):")
for i in range(3):
    print(f"样本{i+1}: 目标1={y[i][0]:.3f}, 目标2={y[i][1]:.3f}, 目标3={y[i][2]:.3f}")

print(f"\n📈 数据统计:")
print(f"特征范围: [{X.min():.3f}, {X.max():.3f}]")
print(f"目标1范围: [{y[:, 0].min():.3f}, {y[:, 0].max():.3f}]")
print(f"目标2范围: [{y[:, 1].min():.3f}, {y[:, 1].max():.3f}]")
print(f"目标3范围: [{y[:, 2].min():.3f}, {y[:, 2].max():.3f}]")

print(f"\n💡 数据说明:")
print("- 这是sklearn生成的合成数据，不是真实数据集")
print("- 10个特征中，前5个对目标有影响，后5个是噪声")
print("- 需要同时预测3个相关的连续数值目标")

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

print(f"\n✂️ 数据分割结果:")
print(f"训练集: X_train{X_train.shape}, y_train{y_train.shape}")
print(f"测试集: X_test{X_test.shape}, y_test{y_test.shape}")

############################################################################
# Build and fit a regressor
# =========================

print(f"\n🤖 开始AutoML训练...")
print("配置参数:")
print("- 总训练时间: 120秒 (2分钟)")
print("- 单个模型时间限制: 30秒")
print("- 数据集名称: synthetic (合成数据)")

automl = AutoSklearnRegressor(
    time_left_for_this_task=120,
    per_run_time_limit=30,
    tmp_folder="/tmp/autosklearn_multioutput_regression_example_tmp",
)

print("\n正在训练模型，请等待...")
automl.fit(X_train, y_train, dataset_name="synthetic")
print("✅ 训练完成!")

############################################################################
# View the models found by auto-sklearn
# =====================================

print(f"\n📊 AutoML找到的最佳模型排行榜:")
print("="*50)
print(automl.leaderboard())

############################################################################
# Print the final ensemble constructed by auto-sklearn
# ====================================================

print(f"\n🏆 最终集成模型详情:")
print("="*50)
pprint(automl.show_models(), indent=4)

###########################################################################
# Get the Score of the final ensemble
# ===================================

predictions = automl.predict(X_test)

print(f"\n📈 模型性能评估:")
print("="*30)
print(f"整体R²分数: {r2_score(y_test, predictions):.4f}")

# 分别评估每个目标的性能
for i in range(3):
    r2_individual = r2_score(y_test[:, i], predictions[:, i])
    print(f"目标{i+1}的R²分数: {r2_individual:.4f}")

print(f"\n🔍 预测结果示例 (前3个测试样本):")
for i in range(3):
    print(f"样本{i+1}:")
    print(f"  真实值: [{y_test[i][0]:.3f}, {y_test[i][1]:.3f}, {y_test[i][2]:.3f}]")
    print(f"  预测值: [{predictions[i][0]:.3f}, {predictions[i][1]:.3f}, {predictions[i][2]:.3f}]")

###########################################################################
# Get the configuration space
# ===========================

print(f"\n⚙️ 算法配置空间:")
print("="*40)
print("AutoML搜索的算法和参数范围:")
print(automl.get_configuration_space(X_train, y_train))

print(f"\n🎯 总结:")
print("="*20)
print("- 成功训练了多输出回归模型")
print("- 能够同时预测3个相关的数值目标")
print("- AutoML自动选择了最佳算法和参数组合")
print("- R²分数越接近1.0，模型性能越好")
